#include <stdlib.h>
#include <string.h>
#include <_string.h>
#include <ctype.h>

/*
 * IN presents the current character is within a word
 */
enum STATUS{
    OUT = 0,
    IN
};
/*
 * reverse_sentence: reverse the order of words in a sentence, keep the words unchanged 
 *
 * return a non-NULL for the after-reversed sentence, NULL for any failure
 */
char * reverse_sentence(char * s)
{
    int i, j;
    int len;
    int end; 	/* ending index of a word */
    char * t;
    enum STATUS flag;

    if (!s) return NULL;

    len = (int)strlen(s);
    t = (char *)malloc(sizeof(char) * (len+1));
    if (!t) return NULL;
    t[len] = '\0';

    for (flag = OUT, i = len-1, j = 0; i >= 0; i--) {
	if (isspace(s[i])) {
	    if (IN == flag) {
		flag = OUT;
#if defined(_GNUC)
		strncpy(t+j, s+i+1, end-i);
#elif defined(_MSVC)
		strncpy_s(t+j, len+1, s+i+1, end-i);
#else
#error "Unsupported compiler environment!"
#endif
		j += end-i;
	    }
    	    t[j++] = s[i];
	} else if (OUT == flag) {
    	    flag = IN; end = i;
	}
    }
    if (IN == flag) { // handle the last word starting at s[0]
#if defined(_GNUC)
	strncpy(t+j, s, end+1); j += end+1;
#elif defined(_MSVC)
	strncpy_s(t+j, len+1, s, end+1); j += end+1;
#else
#error "Unsupported compiler environment!"
#endif
    }

    return t;
}


